package com.platform.cdcs.fragment.stock;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.activity.StockScanActivity;
import com.platform.cdcs.fragment.ProductFragment;
import com.platform.cdcs.fragment.choose.PHFragment;
import com.platform.cdcs.fragment.choose.ProductTypeFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.HouseItem;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.CacheTool;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.platform.cdcs.widget.ChooseWindow;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.TimeDialogBuilder;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/9/30.
 */
public class AddProductFragment extends BaseFragment {

    private int model;
    private String[] unitArray, stockarray;

    private EditText unitET;
    private View titleView;
    private EditText nameET, codeET, beginET, endET, numET, posET;
    private List<ChooseItem> items;
    private String distCode, distName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            model = getArguments().getInt("model");
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initView(View view) {
        titleView = getActivity().findViewById(R.id.title);
        setHasOptionsMenu(true);
        initLoadImg(view.findViewById(R.id.load));
        if (model == 0) {
            setTitle("手动添加入库产品");
        } else {
            setTitle("手动添加出库产品");
        }
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        LayoutInflater inflater = LayoutInflater.from(getContext());
        LinearLayout rootView1 = (LinearLayout) view.findViewById(R.id.button1);

        if (model == 1) {
            posET = ViewTool.createEditItem(inflater, "库位", rootView1, true, true);
            posET.setHint("请选择库位");
            posET.setText("全部");
            posET.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    requestStock();
                }
            });
            posET.setTag("");
        }

        nameET = ViewTool.createEditItem(inflater, "产品型号", rootView1, true, true);
        nameET.setHint("请选择产品型号");
        nameET.setTag("");
        nameET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putString("class", AddProductFragment.this.getClass().getName());
                bundle.putBoolean("hideunit", true);
                FragmentUtil.navigateToInNewActivity(getActivity(), ProductTypeFragment.class, bundle);
            }
        });
        codeET = ViewTool.createEditItemNoLine(inflater, "批号", rootView1, false, false);
        codeET.setHint("请填写产品批号");
        ViewGroup group = (ViewGroup) codeET.getParent();
        TextView textView = (TextView) group.findViewById(R.id.title1);
        textView.setText("批号 （点击选择）");
//        if (model == 0) {
//        } else {
//            codeET = ViewTool.createEditItemNoLine(inflater, "批号", rootView1, false, true);
//            codeET.setHint("请选择产品批号");
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(nameET.getText().toString())) {
                    Utils.showToast(getContext(), "请选选择产品型号！");
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("class", AddProductFragment.this.getClass().getName());
                bundle.putString("code", nameET.getText().toString());
                if (model == 1) {
                    if ("全部".equals(posET.getText().toString())) {
                        bundle.putString("pos", "");
                    } else {
                        bundle.putString("pos", posET.getText().toString());
                    }
                }
                FragmentUtil.navigateToInNewActivity(getActivity(), PHFragment.class, bundle);
            }
        });
//        }

        LinearLayout rootView2 = (LinearLayout) view.findViewById(R.id.button2);
        beginET = ViewTool.createEditItem(inflater, "生产日期", rootView2, false, true);
        beginET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String time = beginET.getText().toString();
                if (TextUtils.isEmpty(time)) {
                    time = Utils.currentTime();
                }
                new TimeDialogBuilder(getContext()).showDate().setTime(time).setCallback(new TimeDialogBuilder.TimePickCallback() {
                    @Override
                    public void setTime(String time) {
                        if (time.compareTo(Utils.currentDate()) > 0) {
                            Utils.showToast(getContext(), "生产日期不能大于当前日期!");
                            return;
                        }
                        if (!TextUtils.isEmpty(endET.getText().toString()) && time.compareTo(endET.getText().toString()) > 0) {
                            Utils.showToast(getContext(), "生产日期不能大于失效日期!");
                            return;
                        }
                        beginET.setText(time);
                    }
                }).create().show();
            }
        });

        endET = ViewTool.createEditItem(inflater, "失效日期", rootView2, false, true);
        endET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String time = endET.getText().toString();
                if (TextUtils.isEmpty(time)) {
                    time = Utils.currentTime();
                }
                new TimeDialogBuilder(getContext()).showDate().setTime(time).setCallback(new TimeDialogBuilder.TimePickCallback() {
                    @Override
                    public void setTime(String time) {
                        if (!TextUtils.isEmpty(beginET.getText().toString()) && time.compareTo(beginET.getText().toString()) < 0) {
                            Utils.showToast(getContext(), "失效日期不能小于生产日期!");
                            return;
                        }
                        endET.setText(time);
                    }
                }).create().show();
            }
        });
        unitET = ViewTool.createEditItemNoLine(inflater, "销售单位", rootView2, true, true);
        unitET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUnit();
            }
        });
        LinearLayout rootView3 = (LinearLayout) view.findViewById(R.id.button3);
        numET = ViewTool.createEditItemNoLine(inflater, model == 0 ? "入库数量" : "出库数量", rootView3, true, false);
        numET.setHint("请输入数量");
        numET.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        numET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String data = numET.getText().toString();
                if (data.contains(".") && !data.endsWith(".") && data.substring(data.indexOf(".") + 1, data.length()).length() > 7) {
                    numET.setText(data.substring(0, data.indexOf(".") + 8));
                    numET.setSelection(numET.getText().length());
                }
            }
        });
        view.findViewById(R.id.button4).setVisibility(View.GONE);
        view.findViewById(R.id.button5).setVisibility(View.GONE);

        TextView btn2 = (TextView) view.findViewById(R.id.text);
        btn2.setText("完成");
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                post();
            }
        });
    }

    private void post() {
        if (TextUtils.isEmpty(nameET.getText().toString())) {
            Utils.showToast(getContext(), "产品型号不能为空！");
            return;
        }
        if (TextUtils.isEmpty(unitET.getText().toString())) {
            Utils.showToast(getContext(), "单位不能为空！");
            return;
        }
        if (TextUtils.isEmpty(numET.getText().toString().trim())) {
            Utils.showToast(getContext(), model == 0 ? "入库数量不能为空!" : "出库数量不能为空");
            return;
        }
        ProductList.ProductItem item = new ProductList.ProductItem();
        item.setMaterialNumber(nameET.getText().toString());
        item.setMaterialName((String) nameET.getTag());
        item.setLots(codeET.getText().toString());
        item.setDomDate(beginET.getText().toString());
        item.setExpDate(endET.getText().toString());
        if (!TextUtils.isEmpty(unitET.getText().toString())) {
            item.setUom(unitET.getText().toString().substring(0, unitET.getText().toString().lastIndexOf(" ")));
        } else {
            item.setUom("");
        }
        item.setQty(numET.getText().toString());
        item.setNowqty(numET.getText().toString());
        if (model == 1) {
            item.setWhCode((String) posET.getTag());
            item.setWhName(posET.getText().toString());
        }
        item.setDistCode(TextUtils.isEmpty(distCode) ? "" : distCode);
        item.setDistName(TextUtils.isEmpty(distName) ? "" : distName);
        CacheTool.append(getActivity(), item, model);
        CacheTool.saveCache(getActivity(), model);
        Utils.showToast(getContext(), "添加成功");
        RefershEvent event = new RefershEvent();
        event.mclass = ProductFragment.class;
        EventBus.getDefault().post(event);
        getActivity().finish();
        Bundle bundle = new Bundle();
        bundle.putInt("model", model);
        FragmentUtil.navigateToInNewActivity(getActivity(), EditProductFragment.class, bundle);

    }

    @Override
    protected void initMenu(Menu menu, MenuInflater inflater) {
        menu.add(0, 0, 0, "扫码添加").setTitle("扫码添加").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                Intent intent = new Intent(getContext(), StockScanActivity.class);
                intent.putExtra("model", model);
                startActivity(intent);
                getActivity().finish();
                return false;
            }
        }).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }

    @Override
    public int layoutId() {
        return R.layout.five_layout;
    }

    private void showUnit() {
        if (TextUtils.isEmpty(nameET.getText().toString())) {
            Utils.showToast(getContext(), "请先选择产品型号");
            return;
        }
        if (unitArray == null) {
            requestUnit();
        } else {
            new TwDialogBuilder(getContext()).setItems("选择单位", unitArray, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    unitET.setText(unitArray[i]);
                }
            }).create().show();
        }
    }

    private void requestUnit() {
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("reqType", "3");
        map.put("itemCode", nameET.getText().toString());
        getHttpClient().post().url(Constant.DIC_URL).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                try {
                    JSONObject obj = new JSONObject(s).getJSONObject("result");
                    if ("1".equals(obj.getString("code"))) {
                        JSONArray jsonArray = obj.getJSONArray("uomList");
                        unitArray = new String[jsonArray.length()];
                        for (int j = 0; j < jsonArray.length(); j++) {
                            if (!TextUtils.isEmpty(jsonArray.getJSONObject(j).getString("uomName"))) {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " (" + jsonArray.getJSONObject(j).getString("uomName") + ")";
                            } else {
                                unitArray[j] = jsonArray.getJSONObject(j).getString("uom") + " ";
                            }
                        }
                        showUnit();
                    } else {
                        Utils.showToast(getContext(), obj.getString("msg"));
                    }
                } catch (Exception e) {
                    Utils.showToast(getContext(), "解析失败");
                    unitArray = null;
                }
            }
        });
    }

    /**
     * 库位
     */
    private void requestStock() {
        showLoadImg();
        getHttpClient().post().url(Constant.DIST_WHHOUSE_LST).params(Constant.makeParam(new HashMap<String, String>())).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                Type type = new TypeToken<BaseObjResponse<HouseItem.HouseList>>() {
                }.getType();
                BaseObjResponse<HouseItem.HouseList> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    items = new ArrayList<ChooseItem>();
                    ChooseItem chooseItem = null;
                    for (HouseItem item : response.getResult().getHouseList()) {
                        if ("1".equals(item.getIsMainHouse())) {
                            chooseItem = new ChooseItem();
                            chooseItem.setTitle(item.getWhName());
                            chooseItem.setTime(item.getWhCode());
                            items.add(0, chooseItem);
                        } else {
                            chooseItem = new ChooseItem();
                            chooseItem.setTitle(item.getWhName());
                            chooseItem.setTime(item.getWhCode());
                            items.add(chooseItem);
                        }
                    }
                    stockarray = new String[items.size()];
                    for (int j = 0; j < items.size(); j++) {
                        stockarray[j] = items.get(j).getTitle();
                    }
                    showStock();
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }

            }
        });
    }

    private void showStock() {
        if (stockarray == null) {
            requestStock();
        } else {
            new TwDialogBuilder(getContext()).setItems(stockarray, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    posET.setText(stockarray[i]);
                    posET.setTag(items.get(i).getTime());
                }
            }, "").create().show();
        }
    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == AddProductFragment.class) {
            if (event.oclass == PHFragment.class) {
                ProductList.ProductItem item = (ProductList.ProductItem) event.bundle.getSerializable("model");
                codeET.setText(item.getLots());
                beginET.setText(item.getProductDate());
                endET.setText(item.getExpDate());
            } else if (event.oclass == ProductTypeFragment.class) {
                ProductList.ProductItem item = (ProductList.ProductItem) event.bundle.getSerializable("model");
                nameET.setText(item.getMaterialNumber());
                nameET.setTag(item.getMaterialName());
                distCode = item.getDistCode();
                distName = item.getDistName();
                codeET.setText("");
                beginET.setText("");
                endET.setText("");
                unitArray = null;
                unitET.setText("");
            }
        }
    }

}
